package com.heima.juc.unlock;

import com.heima.juc.n2.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @author : leimingchao
 * @date Date : 2022年02月12日 19:41
 */
@Slf4j(topic = "c.Test4")
public class Test4 {

    public static void main(String[] args) {

        GarbageBag garbageBag = new GarbageBag("装满了垃圾");
        //参数2 mark 可以看作一个标记，表示垃圾袋满了
        AtomicMarkableReference<GarbageBag> reference = new AtomicMarkableReference<>(garbageBag,true);

        log.debug("start...");
        GarbageBag prev = reference.getReference();
        log.debug(prev.toString());


        new Thread(() -> {
            log.debug("start.....");
            garbageBag.setDesc("空垃圾袋");
            reference.compareAndSet(garbageBag, garbageBag, true, false);
            log.debug(garbageBag.toString());
        }, "保洁阿姨").start();

        Sleeper.sleep(1);

        log.debug("想换一只新垃圾袋？");
        boolean success = reference.compareAndSet(prev, new GarbageBag("空垃圾袋"), true, false);

        log.debug("换了么？" + success);
        log.debug(reference.getReference().toString());
    }
}

class GarbageBag {

    String desc;

    public GarbageBag(String desc) {
        this.desc = desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return super.toString() + " " + desc;
    }
}
